import { createRouter, createWebHashHistory } from 'vue-router'
import Dashboard from '../components/Admin/Dashboard.vue'
import Login from '../components/Admin/Login.vue'
import ProductsManagement from '../components/Admin/ProductsManagement.vue'
import NewsManagement from '../components/Admin/NewsManagement.vue'
import OrdersManagement from '../components/Admin/OrdersManagement.vue'
import CustomersManagement from '../components/Admin/CustomersManagement.vue'
import ReviewsManagement from '../components/Admin/ReviewsManagement.vue'
import SettingsManagement from '../components/Admin/SettingsManagement.vue'
import CarouselManagement from '../components/Admin/CarouselManagement.vue'
import CompanyManagement from '../components/Admin/CompanyManagement.vue'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('../components/HomePage.vue')
  },
  {
    path: '/admin-login',
    name: 'AdminLogin',
    component: Login,
    meta: {
      public: true
    }
  },
  {
    path: '/admin-dashboard',
    name: 'AdminDashboard',
    component: Dashboard,
    meta: {
      requiresAuth: true
    }
  },
  {
    path: '/admin-products',
    name: 'AdminProducts',
    component: ProductsManagement,
    meta: {
      requiresAuth: true
    }
  },
  {
    path: '/admin-news',
    name: 'AdminNews',
    component: NewsManagement,
    meta: {
      requiresAuth: true
    }
  },
  {
    path: '/admin-orders',
    name: 'AdminOrders',
    component: OrdersManagement,
    meta: {
      requiresAuth: true
    }
  },
  {
    path: '/admin-customers',
    name: 'AdminCustomers',
    component: CustomersManagement,
    meta: {
      requiresAuth: true
    }
  },
  {
    path: '/admin-reviews',
    name: 'AdminReviews',
    component: ReviewsManagement,
    meta: {
      requiresAuth: true
    }
  },
  {
    path: '/admin-settings',
    name: 'AdminSettings',
    component: SettingsManagement,
    meta: {
      requiresAuth: true
    }
  },
  {
    path: '/admin-carousel',
    name: 'AdminCarousel',
    component: CarouselManagement,
    meta: {
      requiresAuth: true
    }
  },
  {
    path: '/admin-company',
    name: 'AdminCompany',
    component: CompanyManagement,
    meta: {
      requiresAuth: true
    }
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
  
  if (to.meta.requiresAuth && !isLoggedIn) {
    next('/admin-login')
  } else if (to.meta.public && isLoggedIn && to.path !== '/admin-login') {
    next('/admin-dashboard')
  } else {
    next()
  }
})

export default router